package com.jzoom.zoom.excel;

import com.jzoom.zoom.common.io.Io;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;

public class ExcelTable {

	HSSFWorkbook hwb;
	// 这里进行创建excel
	HSSFSheet sheet;
	int cols = 0;
	int startIndex = 0;

	public ExcelTable() {
		hwb = new HSSFWorkbook();
	}

	public void writeTo(OutputStream outputStream) throws IOException {
		hwb.write(outputStream);
	}
	
	

	public ExcelTable createSheet(String name) {
		sheet = hwb.createSheet(name);
		startIndex = 0;
		return this;
	}
	
	public ExcelTable setSheet(int index){
		hwb.setActiveSheet(index);
		sheet = hwb.getSheetAt(index);
		return this;
	}

	public ExcelTable save(File file) throws IOException {

		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			hwb.write(out);
			return this;
		} finally {
			Io.close(out);
		}
	}
	
	public void write(OutputStream outputStream) throws IOException{
		hwb.write(outputStream);
	}

	public void close() throws IOException {
		if (hwb != null)
			hwb.close();
	}

	public ExcelTable addRow(String[] cols) {
		this.cols = cols.length;
		HSSFRow row = sheet.createRow(startIndex++);
		int index = 0;
		for (String val : cols) {
			HSSFCell cell = row.createCell(index++);
			cell.setCellValue(val);
		}
		return this;
	}
	
	

	public int getIndex(){
		return startIndex;
	}

	public ExcelTable addRow(Collection<String> cols) {
		this.cols = cols.size();
		HSSFRow row = sheet.createRow(startIndex++);
		int i = 0;
		for (String val : cols) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(val);
			++i;
		}
		return this;
	}


	/**
	 * 增加一个标题 ( 全部合并的 ）
	 * @param value
	 * @param columnCount
	 * @return
	 */
	public ExcelTable addTitle(String value, int columnCount) {
		CellStyle style = hwb.createCellStyle();
		style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		HSSFRow row = sheet.createRow(startIndex);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue(value);
		cell.setCellStyle(style);
		
		CellRangeAddress cra = new CellRangeAddress(startIndex, startIndex, 0, columnCount);
		// 在sheet里增加合并单元格
		sheet.addMergedRegion(cra);
		++startIndex;
		return this;
	}

}
